package com.base.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.constant.Constants;
import com.base.domain.SysRole;
import com.base.enums.DeletedEnum;
import com.base.mapper.SysRoleMapper;
import com.base.service.SysRoleService;
import com.base.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author gxd
 * @since 2025/6/6
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    /**
     * 分页列表-角色列表
     * @param role 角色查询条件
     * @return 角色列表
     */
    @Override
    public List<SysRole> pageList(SysRole role) {
        List<SysRole> list = this.list(
                Wrappers.lambdaQuery(SysRole.class)
                        .eq(SysRole::getDeleted, DeletedEnum.NO.getCode())
                        .like(StrUtil.isNotBlank(role.getRoleName()), SysRole::getRoleName, role.getRoleName())
                        .like(StrUtil.isNotBlank(role.getRoleKey()), SysRole::getRoleKey, role.getRoleKey())
                        .eq(ObjUtil.isNotNull(role.getStatus()), SysRole::getStatus, role.getStatus())
                        .gt(StrUtil.isNotBlank(role.getStartTime()), SysRole::getCreateTime, StrUtil.isNotBlank(role.getStartTime()) ? DateUtil.beginOfDay(DateUtil.parse(role.getStartTime(), Constants.YYYY_MM_DD)) : null)
                        .lt(StrUtil.isNotBlank(role.getEndTime()), SysRole::getCreateTime, StrUtil.isNotBlank(role.getEndTime()) ? DateUtil.endOfDay(DateUtil.parse(role.getEndTime(), Constants.YYYY_MM_DD)) : null)
                        .orderByAsc(SysRole::getSort)
        );
        return list;
    }


    /**
     * 添加或修改-角色信息
     * @param role 角色实体
     * @return 角色信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysRole addOrEdit(SysRole role) {
        Assert.notNull(role, "角色信息不能为空");
        if (ObjUtil.isNotNull(role.getId())) {
            SysRole roleInfo = Assert.notNull(this.getById(role.getId()), "要修改的角色记录不存在");
            BeanUtils.copyNotEmptyProperties(role, roleInfo);
            this.updateById(roleInfo);
            return roleInfo;
        }

        role.setDeleted(DeletedEnum.NO.getCode());
        this.save(role);
        return role;
    }
}
